package sandbox.service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.slim3.datastore.Datastore;
import org.slim3.datastore.EntityNotFoundRuntimeException;

import sandbox.meta.RankingMeta;
import sandbox.model.Ranking;
import sandbox.model.SampleInfo;

public class RankingService {

    public static void click(SampleInfo sampleInfo) {
        Ranking ranking = new Ranking();
        ranking.setKey(Datastore.createKey(RankingMeta.get(), "ranking"));
        ranking.setCounters(new ArrayList<Ranking.Counter>());
        try {
            ranking = Datastore.get(RankingMeta.get(), ranking.getKey());
        } catch (EntityNotFoundRuntimeException e) {
        }

        Ranking.Counter counter = new Ranking.Counter();
        counter.setKey(Datastore.keyToString(sampleInfo.getKey()));
        counter.setTitle(sampleInfo.getTitle());

        int index = ranking.getCounters().indexOf(counter);
        if (index < 0) {
            ranking.getCounters().add(counter);
        } else {
            counter = ranking.getCounters().get(index);
        }
        counter.setCounter(counter.getCounter() + 1);

        Datastore.put(ranking);
    }

    public static int getRanking(SampleInfo sampleInfo) {
        if (sampleInfo == null) {
            return 0;
        }

        List<Ranking.Counter> ranking = getRankingList();
        if (ranking == null || ranking.isEmpty()) {
            return 0;
        }

        Ranking.Counter counter = new Ranking.Counter();
        counter.setKey(Datastore.keyToString(sampleInfo.getKey()));
        counter.setTitle(sampleInfo.getTitle());
        return ranking.indexOf(counter) + 1;
    }

    public static List<Ranking.Counter> getRankingList() {
        try {
            List<Ranking.Counter> result = Datastore.get(RankingMeta.get(), Datastore.createKey(RankingMeta.get(), "ranking")).getCounters();
            Collections.sort(result);
            return result;
        } catch (Exception e) {
           return null;
        }
    }

}
